// index.ts
import { getRandomImage } from '../../utils/util';

interface UserInfo {
  nickName: string;
  avatarUrl: string;
}

interface ImageItem {
  id: string;
  prompt: string;
  imageUrl: string;
  height?: number; // 高度可选，将由图片加载后的实际高度决定
  createdAt: number;
  user?: UserInfo; // 添加用户信息
}

// 添加云函数返回类型
interface CloudFunctionResult {
  success: boolean;
  images?: ImageItem[];
  total?: number;
  hasMore?: boolean;
  message?: string;
  error?: any;
}

Page({
  data: {
    imageList: [] as ImageItem[],
    leftColumn: [] as ImageItem[],
    rightColumn: [] as ImageItem[],
    isLoading: false,
    page: 1,
    hasMore: true
  },

  onLoad() {
    // 从云端加载图片列表
    this.loadImagesFromCloud();
  },

  onShow() {
    // Check if there's a new image added through global data
    // This would be set when returning from image result page after publishing
    const app = getApp<{
      globalData: {
        newPublishedImage?: ImageItem;
      };
    }>();
    
    if (app.globalData.newPublishedImage) {
      console.log('发现新发布的图片', app.globalData.newPublishedImage);
      
      // 如果是第一次加载，先确保从服务器加载了图片
      if (this.data.imageList.length === 0) {
        this.setData({
          page: 1,
          hasMore: true
        });
        this.loadImagesFromCloud(() => {
          // 清除全局数据
          app.globalData.newPublishedImage = undefined;
        });
        return;
      }
      
      // 如果已经有图片列表，则直接插入到顶部
      const newImage = app.globalData.newPublishedImage;
      
      // 检查是否已经存在相同ID的图片（避免重复添加）
      const existingIndex = this.data.imageList.findIndex(img => img.id === newImage.id);
      if (existingIndex !== -1) {
        console.log('图片已存在，不重复添加');
        app.globalData.newPublishedImage = undefined;
        return;
      }
      
      // 添加到图片列表顶部
      const updatedList = [newImage, ...this.data.imageList];
      
      this.setData({
        imageList: updatedList
      });
      
      // 将新图片添加到较短的列的顶部
      this.addItemToShortestColumn(newImage, true);
      
      // 清除全局数据
      app.globalData.newPublishedImage = undefined;
    }
  },

  // 从云函数加载图片
  async loadImagesFromCloud(callback?: () => void) {
    if (!this.data.hasMore || this.data.isLoading) {
      callback?.();
      return;
    }

    this.setData({ isLoading: true });

    try {
      const result = await wx.cloud.callFunction({
        name: 'getPublishedImages',
        data: {
          page: this.data.page,
          pageSize: 10
        }
      });
      
      // 类型转换
      const response = result.result as CloudFunctionResult;
      
      if (response && response.success) {
        const newImages = response.images || [];
        
        // 确保按时间最新排序
        if (newImages.length > 0) {
          newImages.sort((a, b) => b.createdAt - a.createdAt);
        }
        
        // 更新列表数据
        const updatedImageList = [...this.data.imageList, ...newImages];
        
        this.setData({
          imageList: updatedImageList,
          isLoading: false,
          page: this.data.page + 1,
          hasMore: response.hasMore || false
        });
        
        // 将新加载的图片分配到两列
        // 如果是第一页，确保图片排序是最新在前
        if (this.data.page === 1) {
          this.setData({
            leftColumn: [],
            rightColumn: []
          });
          this.distributeImagesToColumns(updatedImageList);
        } else {
          this.distributeImagesToColumns(newImages);
        }
      } else {
        console.error('获取图片列表失败:', response?.message || '未知错误');
        this.setData({ isLoading: false });
      }
    } catch (err) {
      console.error('调用云函数获取图片列表失败:', err);
      this.setData({ isLoading: false });
    }
    
    callback?.();
  },

  // 将图片分配到左右两列
  distributeImagesToColumns(images: ImageItem[]) {
    // 将新图片依次添加到较短的列
    images.forEach(image => {
      this.addItemToShortestColumn(image);
    });
  },
  
  // 将单个图片添加到较短的列
  addItemToShortestColumn(image: ImageItem, addToTop: boolean = false) {
    const { leftColumn, rightColumn } = this.data;
    
    // 决定放到哪一列（优先放到元素较少的列，以保持平衡）
    if (leftColumn.length <= rightColumn.length) {
      this.setData({
        leftColumn: addToTop ? [image, ...leftColumn] : [...leftColumn, image]
      });
    } else {
      this.setData({
        rightColumn: addToTop ? [image, ...rightColumn] : [...rightColumn, image]
      });
    }
  },
  
  // 监听图片加载完成事件，如果需要可以记录图片实际高度
  onImageLoad(e: any) {
    // 可以用于记录图片的实际宽高比，如果需要的话
    // console.log('Image loaded', e.detail);
  },

  onPullDownRefresh() {
    // Reset pagination and reload
    this.setData({
      page: 1,
      imageList: [],
      leftColumn: [],
      rightColumn: [],
      hasMore: true
    });
    this.loadImagesFromCloud(() => {
      wx.stopPullDownRefresh();
    });
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.isLoading) {
      this.loadImagesFromCloud();
    }
  },

  onCreateImage() {
    wx.navigateTo({
      url: '/pages/createImage/index'
    });
  },

  // 点击图片，跳转到详情页
  onImageTap(e: any) {
    const image = e.currentTarget.dataset.image;
    if (!image || !image.id) return;
    
    console.log('Image tapped:', image);
    
    wx.navigateTo({
      url: `/pages/imageDetail/index?id=${image.id}`,
      success: (res) => {
        // 将完整的图片数据传递给详情页
        res.eventChannel.emit('passImageData', { image });
      }
    });
  }
}); 